package com.example.hotel.blImpl.security;

import com.example.hotel.bl.user.AccountService;
import com.example.hotel.data.security.PermissionMapper;
import com.example.hotel.po.User;
import com.example.hotel.vo.LoginUser;
import com.example.hotel.vo.Permission;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AccountService accountService;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        User userInfo = accountService.getUserInfo(username);   // 实际是email

        if (userInfo == null) {
            throw new AuthenticationCredentialsNotFoundException("用户不存在");
        }

        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(userInfo, loginUser);
        loginUser.setUserName(userInfo.getEmail());

        // TODO: Permissions
        List<Permission> permissions = permissionMapper.queryPermissionsById(userInfo.getId());
        loginUser.setPermissions(permissions);
        System.out.println(permissions);

        return loginUser;
    }
}
